package com.smfx.yxt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smfx.yxt.common.AdminUser;
import com.smfx.yxt.common.Configuration;
import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.Constants;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.WechatConfigure;
import com.smfx.yxt.common.enums.ResourceType;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.common.enums.StudentSignUpType;
import com.smfx.yxt.model.ClassTeachers;
import com.smfx.yxt.model.ComboBox;
import com.smfx.yxt.model.OrganizeDepart;
import com.smfx.yxt.model.ParentInfo;
import com.smfx.yxt.model.StudentSignUp;
import com.smfx.yxt.model.SysUserRole;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.model.TeacherSignUp;
import com.smfx.yxt.reqVo.BaseQueryVO;
import com.smfx.yxt.service.IClassTeachersService;
import com.smfx.yxt.service.IHkFaceGroupService;
import com.smfx.yxt.service.IParentService;
import com.smfx.yxt.service.IStudentSignUpService;
import com.smfx.yxt.service.ISysUserRoleService;
import com.smfx.yxt.service.ITeacherService;
import com.smfx.yxt.service.ITeacherSignUpService;
import com.smfx.yxt.utils.FileUtils;
import com.smfx.yxt.utils.HkFaceUtil;
import com.smfx.yxt.utils.MimeTypeUtils;
import com.smfx.yxt.utils.PropertiesUtil;
import com.smfx.yxt.utils.RequestUtil;
import com.smfx.yxt.utils.StringUtil;
import com.smfx.yxt.utils.TextUtil;
import com.smfx.yxt.view.ParentRelStudentView;
import com.smfx.yxt.vo.WxsndRecive;
import com.smfx.yxt.wechat.model.WechatSnsToken;
import com.smfx.yxt.wechat.model.WechatUserInfo;
import com.smfx.yxt.wechat.utils.TemplateUtil;
import com.smfx.yxt.wechat.utils.WechatGlobalMap;
import com.smfx.yxt.wechat.utils.WechatUtils;

@RequestMapping("common")
@Controller
public class CommonController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(CommonController.class);
	
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private IStudentSignUpService studentSignUpService;
	@Autowired
	private ITeacherSignUpService teacherSignUpService;
	@Autowired
	private IClassTeachersService classTeachersService;
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private IParentService parentService;
	@Autowired
	private IHkFaceGroupService hkFaceGroupService;
	
	@RequestMapping("getModel")
	@ResponseBody Object getModel() {
		return WechatUtils.getWechatModel();
	}
	
	@RequestMapping("faceGroup")
	@ResponseBody Object faceGroup() {
		String groupType = request.getParameter("groupType");
		return hkFaceGroupService.selectListByGroupType(groupType);
	}
	
	@RequestMapping("setTeacherUnionid")
	@ResponseBody Object setTeacherUnionid() {
		try {
			List<TeacherInfo> list = teacherService.selectList();
			for(TeacherInfo record : list) {
				if(StringUtils.isNotBlank(record.getOpenid2())) {
					WechatUserInfo userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(), record.getOpenid2());
					if(userInfo != null) {
						record.setUnionid(userInfo.getUnionid());
						teacherService.updateById(record);
					}
				}
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("setStudentUnionid")
	@ResponseBody Object setStudentUnionid() {
		try {
			List<ParentInfo> list = parentService.selectList();
			for(ParentInfo record : list) {
				if(StringUtils.isNotBlank(record.getOpenid())) {
					WechatUserInfo userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(), record.getOpenid());
					if(userInfo != null) {
						record.setUnionid(userInfo.getUnionid());
						parentService.updateForParent(record);
					}
				}
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("role/list")
	@ResponseBody Object roleList() {
		try {
			List<ComboBox> list = new ArrayList<>();
			list.add(new ComboBox("0", "请选择"));
			List<SysUserRole> roleList = sysUserRoleService.selectAll();
			for(SysUserRole role : roleList) {
				list.add(new ComboBox(String.valueOf(role.getId()), role.getRoleName()));
			}
			return list;
		} catch (Exception e) {
			logger.error("---roleList error={}", e);
		}
		return null;
	}
	
	@RequestMapping("getClazz")
	@ResponseBody Object getClazz() {
		try {
			BaseQueryVO vo = new BaseQueryVO();
			String grade = request.getParameter("grade");
			vo.setGrade(StringUtils.isNotBlank(grade) ? Integer.valueOf(grade) : 0);
			AdminUser user = (AdminUser) request.getSession().getAttribute(Constants.ADMIN_USER);
			vo.setSchoolId(user.getTeacherInfo().getSchoolId());
			vo.setFinishYear(getCurrentTerm().getFinishYear());
			List<ClassTeachers> listData = classTeachersService.selectClassList(vo);
			List<ComboBox> list = new ArrayList<>();
			list.add(new ComboBox("", "请选择"));
			for(ClassTeachers teachers : listData) {
				list.add(new ComboBox(String.valueOf(teachers.getClazz()), String.valueOf(teachers.getClazz())+"班"));
			}
			return list;
		} catch (Exception e) {
			logger.error("--error={}", e);
		}
		return null;
	}
	
	@RequestMapping("resourceType")
	@ResponseBody Object resourseType() {
		List<ComboBox> list = new ArrayList<>();
		list.add(new ComboBox(ResourceType.MENU.getCode(), ResourceType.MENU.getValue()));
		list.add(new ComboBox(ResourceType.PAGE.getCode(), ResourceType.PAGE.getValue()));
		list.add(new ComboBox(ResourceType.BUTTON.getCode(), ResourceType.BUTTON.getValue()));
		return list;
	}
	
	@RequestMapping("updatePosition")
	@ResponseBody Object updatePosition() {
		try {
			List<TeacherInfo> list = teacherService.selectList();
			BaseQueryVO vo = new BaseQueryVO();
			vo.setFinishYear(getCurrentTerm().getFinishYear());
			vo.setSchoolId(1);
			List<ClassTeachers> ctList = classTeachersService.selectClassList(vo);
			Map<String, OrganizeDepart> map = (Map<String, OrganizeDepart>) WechatGlobalMap.get(Const.CACHE_ORGANIZE_DEPART).getValue();
			for(TeacherInfo info : list) {
				List<String> plList = new ArrayList<>();
				String position = info.getPosition();
				if(StringUtils.isNotBlank(position)) {
					String[] strings = position.split(",");
					for(int i = 0; i < strings.length; i++) {
						if(!(strings[i].equals("3005") || strings[i].equals("3007") ||
								strings[i].equals("3010"))) {
							plList.add(strings[i]);
						}
					}
				}
				for(ClassTeachers ct : ctList) {
					if(ct.getClassTeacherId().intValue() == info.getId().intValue()) {
						plList.add("3005");
					}else if(ct.getDeputyClassTeacher().equals(info.getName())) {
						plList.add("3010");
					}else if(ct.getLifeTeacher().equals(info.getName())) {
						plList.add("3007");
					}
					if(ct.getChineseTeacher().equals(info.getName()) || 
							ct.getEnglishTeacher().equals(info.getName()) ||
							ct.getMathTeacher().equals(info.getName())) {
						if(!StringUtil.isExist(info.getPosition(), "3006") && !StringUtil.isExist(String.join(",", plList), "3006")) {
							plList.add("3006");
						}
					}
				}
				List<String> dList = new ArrayList<>();
				for(int i = 0; i < plList.size(); i++) {
					if(map.containsKey(plList.get(i))){
						dList.add(String.valueOf(map.get(plList.get(i)).getParentId()));
					}
				}
				info.setDepart(dList.size() > 0 ? StringUtil.delRepeatStr(String.join(",", dList)) : null);
				info.setPosition(plList.size() > 0 ? String.join(",", plList) : null);
			}
			teacherService.updateBatchPosition(list);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	/**
	 * 微信关注跳转
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("wechatauth")
	public String wechatauth(HttpServletResponse response, HttpServletRequest request) throws Exception {
		WechatSnsToken snsToken = null;
		WechatUserInfo userInfo = null;
		String code = request.getParameter("code");
		String self = request.getParameter("self");
		if(StringUtils.isNotBlank(code)) {
			snsToken = WechatUtils.getOpenidByCode(code);
			if(snsToken == null) {
				response.sendRedirect(Configuration.getInstance().getWechatAttention());
				return null;
			}
			userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(),
					snsToken.getOpenid());
		}
		if(userInfo != null && userInfo.getSubscribe() == 1) {
			RequestUtil.saveCookie(response, Const.OPENID_COOKIE, userInfo.getOpenid(), (90 * 24 * 60 * 60));
			session.setAttribute(Constants.WECHAT_USERINFO, userInfo);
			userInfo = (WechatUserInfo) request.getSession().getAttribute(Constants.WECHAT_USERINFO);
			return "redirect:" + self;
		}
		response.sendRedirect(Configuration.getInstance().getWechatAttention());
		return null;
	}
	
	@RequestMapping("userOauth2")
	public String userOauth2(HttpServletResponse response, HttpServletRequest request) throws Exception {
		try {
			String code = request.getParameter("code");
			String selfUrl = request.getParameter("self_url");
			if(StringUtils.isNotBlank(code)) {
				WechatSnsToken snsToken = WechatUtils.getOpenidByCode(code);
				selfUrl = URLEncoder.encode(selfUrl+"&openid=" + snsToken.getOpenid());
				request.setAttribute("selfUrl", selfUrl);
				return "redirect";
			}
			response.sendRedirect(getUserOauth2RedirectUrl(selfUrl));
		} catch (Exception e) {
			logger.error("---userOauth2 error={}", e);
		}
		return null;
	}
	
	private static String getUserOauth2RedirectUrl(String selfUrl) {
		WechatConfigure configure = WechatConfigure.getInstance();
		String reUrl = Const.BASEPATH + "/common/userOauth2?self_url=" + selfUrl;
		String url = TextUtil.format(configure.getOauth2Base(), 
				new String[]{configure.getAppid(), URLEncoder.encode(reUrl)});
		return url;
	}
	
	private static String getUserOauth2RedirectUrl() {
		WechatConfigure configure = WechatConfigure.getInstance();
		String selfUrl = Const.BASEPATH + "/common/userOauth2";
		String url = TextUtil.format(configure.getOauth2Base(), 
				new String[]{configure.getAppid(), URLEncoder.encode(selfUrl)});
		return url;
	}
	
	/**
	 * 新生报名
	 * @return
	 */
	@RequestMapping("signUp/newStu")
	public String newStuSignUp(Model model) {
		model.addAttribute("signUpType", StudentSignUpType.NEW_STUDENT.getCode());
		return "signUp/newStu";
	}
	/**
	 * 插班生报名
	 * @return
	 */
	@RequestMapping("signUp/middleStu")
	public String middleStuSignUp(Model model) {
		model.addAttribute("signUpType", StudentSignUpType.MIDDLE_STUDENT.getCode());
		return "signUp/middleStu";
	}
	/**
	 * 国家班报名
	 * @return
	 */
	@RequestMapping("signUp/internatStu")
	public String internatStuSignUp(Model model) {
		model.addAttribute("signUpType", StudentSignUpType.INTERNAT_STUDENT.getCode());
		return "signUp/internatStu";
	}
	@RequestMapping("signUp/teacher")
	public String teacherSignUp(Model model) {
		return "signUp/teacher";
	}
	
	@RequestMapping("signUp/student/submit")
	@ResponseBody Object signUpStudentSubmit(StudentSignUp record) {
		try {
			studentSignUpService.addAndUpdate(record);
			return new RspResult(Status.SUCCESS, record.getId());
		} catch (Exception e) {
			logger.error("---signUpSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("signUp/teacher/submit")
	@ResponseBody Object signUpTeacherSubmit(TeacherSignUp record) {
		try {
			teacherSignUpService.addAndUpdate(record);
			return new RspResult(Status.SUCCESS, record.getId());
		} catch (Exception e) {
			logger.error("---signUpSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("upload")
    public void fileDown(@RequestParam(value="fileName") String fileName, 
    		HttpServletRequest request, HttpServletResponse response) {
    	FileInputStream fis = null;
		OutputStream out = null;
    	try{
    		String tempPath = this.getClass().getClassLoader().getResource("/").getPath();
        	tempPath = tempPath.replace("/WEB-INF/classes", "/template");
        	fileName = URLDecoder.decode(fileName,"UTF-8");
            // 获取文件的扩展名
            String extName = FileUtils.getExtName(fileName);
            // 获取文件类型
            File file = new File(tempPath + fileName);
            if(!file.exists()) {
            	throw new FileNotFoundException();
            }
            //下载报表
			response.setContentType(MimeTypeUtils.getMimeType(extName));
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            String len = String.valueOf(file.length());
            response.setHeader("Content-Length", len);
            out = response.getOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while((n=fis.read(b))!=-1){
                out.write(b, 0, n);
            }
            out.flush();
    	}catch(FileNotFoundException e) {
    		PrintWriter printout;
			try {
				printout = response.getWriter();
				printout.print("<!DOCTYPE html><meta charset=\"UTF-8\" /><script src=\"../js/jquery.min.js\"></script>"
						+"<script src=\"../js/plugin/artDialog/artDialog.source.js?skin=chrome\"></script>"
						+ "<script src=\"../js/common.js\"></script>"
						+ "<body style='font-size:12px'><script language='javascript'>"
						+ "diaAlert('error','抱歉,您选择下载的文档不存在！');setTimeout(function(){history.back();},3000)</script>"
						+ "</body>");
			} catch (IOException e1) {
				logger.error("method downloadReport error:{}",e1);
			}
    	}catch (Exception e) {
			logger.error("文件下载异常,{}", e);
		}finally {
			try {
				if (out != null) {
					out.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				logger.error("method downloadReport close Stream IOException:{}",e);
			}

		}
	}

	/**
	 * 接收推送学生刷卡信息
	 * @auther 胡启萌
	 * @Date 2017年4月17日
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="wx/wxsnd_recive/swwx", method = RequestMethod.POST)  
    @ResponseBody Object swwx(@RequestBody WxsndRecive vo) { 
		try {
			List<ParentRelStudentView> list = parentService.selectParentListByStudentId(Integer.valueOf(vo.getOrg_stu_id()));
			for(ParentInfo parent : list) {
				TemplateUtil.schoolbusStudentSend(parent.getOpenid(), vo.getStu_name(), 
						vo.getAdd_time(), vo.getSchool_name() + vo.getLine_cate(), vo.getType_name(), vo.getPost_url());
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--swwx error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("schoolNotice")
	@ResponseBody Object schoolNotice() {
		String parentIds = request.getParameter("parentIds");
		List<ParentInfo> list = parentService.selectListByIds(Arrays.asList(parentIds.split(",")));
		if(!StringUtil.isNullOrEmpty(list)) {
			String currReqUrl = Const.BASEPATH + Const.STUDENT_ROLE + "/my/faceCollection";
			for(ParentInfo parent : list) {
				TemplateUtil.schoolNoticeSend(parent.getOpenid(), "家长", 
						"石门实验中学附属小学", "学校管理员", "您上传的图片脸部间距太小，请拉近脸部距离再重新上传", 
						PropertiesUtil.getProperty("school_notice_template"), currReqUrl);
			}
			return new RspResult(Status.SUCCESS);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("abc")
	@ResponseBody Object batchUpdatePersonId() {
		try {
			List<ParentInfo> list = new ArrayList<>();
			int count = parentService.selectNoPersonIdCount();
			if(count > 0) {
				int pageNo = 1;
				int pageSize = 500;
				String result = HkFaceUtil.getPersonInfosByPage(1, 500);
				JSONObject json = JSONObject.parseObject(result);
				if("0".equals(json.getString("code"))) {
					JSONObject data = json.getJSONObject("data");
					JSONArray array = data.getJSONArray("list");
					int total = data.getIntValue("total");
					batchUpdate(array, list);
					while (pageNo * pageSize < total) {
						pageNo += 1;
						queryData(pageNo, pageSize,list);
					}
				}
			}
			return JSON.toJSONString(list.size());
		} catch (Exception e) {
			logger.error("---getPersonId error={}", e);
		}
		return null;
	}
	
	private void queryData(int pageNo, int pageSize,List<ParentInfo> list) {
		String result = HkFaceUtil.getPersonInfosByPage(pageNo, pageSize);
		JSONObject json = JSONObject.parseObject(result);
		if("0".equals(json.getString("code"))) {
			JSONObject data = json.getJSONObject("data");
			JSONArray array = data.getJSONArray("list");
			batchUpdate(array,list);
		}
	}
	
	private void batchUpdate(JSONArray array, List<ParentInfo> list) {
		for(int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			String jobNo = json.getString("jobNo");
			//if(jobNo.indexOf("JZ") != -1) {
				ParentInfo parent = new ParentInfo();
				//parent.setId(Integer.valueOf(jobNo.replace("JZ", "")));
				parent.setName(jobNo);
				parent.setFacePersonId(json.getString("personId"));
				list.add(parent);
			//}
		}
	}
}
